using BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore;
using Ordering.Application.Abstractions.Persistence;
using Ordering.Domain.Orders;

namespace Ordering.Infrastructure.Persistence;

public class OrderingDbContext(DbContextOptions<OrderingDbContext> options)
    : DbContext(options), IUnitOfWork
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Order>(builder =>
        {
            builder.ToTable("orders");
            builder.HasKey(order => order.Id);

            builder.Property(order => order.Id)
                .HasColumnName("id");

            builder.Property(order => order.UserId)
                .HasColumnName("user_id")
                .HasColumnType("uuid")
                .IsRequired();

            builder.Property(order => order.Status)
                .HasColumnName("status")
                .HasMaxLength(32)
                .IsRequired();

            builder.Property(order => order.Total)
                .HasColumnName("total")
                .HasColumnType("numeric(18,2)")
                .IsRequired();

            builder.Property(order => order.CreatedAt)
                .HasColumnName("created_at")
                .IsRequired();

            builder.Property(order => order.ShippingAddress)
                .HasColumnName("shipping_address")
                .HasMaxLength(512);

            builder.Property(order => order.Notes)
                .HasColumnName("notes")
                .HasMaxLength(1024);

            builder.OwnsMany(order => order.Items, items =>
            {
                items.ToTable("order_items");
                items.WithOwner().HasForeignKey("order_id");

                items.Property<Guid>("Id")
                    .HasColumnName("id")
                    .ValueGeneratedOnAdd();
                items.HasKey("Id");

                items.Property(item => item.ProductId)
                    .HasColumnName("product_id")
                    .IsRequired();

                items.Property(item => item.ProductName)
                    .HasColumnName("product_name")
                    .HasMaxLength(256)
                    .IsRequired();

                items.Property(item => item.UnitPrice)
                    .HasColumnName("unit_price")
                    .HasColumnType("numeric(18,2)")
                    .IsRequired();

                items.Property(item => item.Quantity)
                    .HasColumnName("quantity")
                    .IsRequired();
            });
        });
    }
}
